package gj.cordova.plugin;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONObject;

import org.apache.cordova.CordovaPlugin;

import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

public class UM extends CordovaPlugin {
    private Activity activity;
    private static String OPENSHARE = "openShare";
    private static String AUTH = "auth";
    private static int WEIXIN = 1;
    private static int QQ = 2;
    private static int WEIBO = 3;
    @Override
    protected void pluginInitialize() {
        Logger.d("init");
        this.activity = cordova.getActivity();
        String UMENG_APPKEY = preferences.getString("UMENG_APPKEY", "");
        String UMENG_CHANNEL = preferences.getString("UMENG_CHANNEL", "");
        if(!UMENG_APPKEY.isEmpty() && !UMENG_CHANNEL.isEmpty()) {
            MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this.activity, UMENG_APPKEY, UMENG_CHANNEL));
        }
        String WEIXIN_KEY = preferences.getString("WEIXIN_KEY", "");
        String WEIXIN_SECRET = preferences.getString("WEIXIN_SECRET", "");
        if(!WEIXIN_SECRET.isEmpty() && !WEIXIN_KEY.isEmpty()) {
            PlatformConfig.setWeixin(WEIXIN_KEY, WEIXIN_SECRET);
        }
        String WEIBO_KEY = preferences.getString("WEIBO_KEY", "");
        String WEIBO_SECRET = preferences.getString("WEIBO_SECRET", "");
        String WEIBO_REDIRECTURL = preferences.getString("WEIBO_REDIRECTURL", "");
        if (!WEIBO_KEY.isEmpty() && !WEIBO_SECRET.isEmpty() && !WEIBO_REDIRECTURL.isEmpty()) {
            PlatformConfig.setSinaWeibo(WEIBO_KEY, WEIBO_SECRET, WEIBO_REDIRECTURL);
        }
        String QQ_ID = preferences.getString("QQ_ID", "");
        String QQ_KEY = preferences.getString("QQ_KEY", "");
        if(!QQ_ID.isEmpty() && !QQ_KEY.isEmpty()) {
            PlatformConfig.setQQZone(QQ_ID, QQ_KEY);
        }
//        Config.DEBUG = true;
    }

    @Override
    public void onPause(boolean multitasking) {
        MobclickAgent.onPause(this.activity);
    }
    
    @Override
    public void onResume(boolean multitasking) {
        MobclickAgent.onResume(this.activity);
    }

    @Override
    public void onDestroy() {

    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
        Logger.d("execute");
        JSONObject obj = args.optJSONObject(0);
        if (action.equals(OPENSHARE)) {
            String title = obj.optString("title");
            String imageUrl = obj.optString("imageUrl");
            String desc = obj.optString("desc");
            openShare(title, imageUrl, desc, callbackContext);
        } else if (action.equals(AUTH)) {
            SHARE_MEDIA platform = getPlatform(obj.optInt("platform"));
            if (platform == null) {
                return false;
            }
            auth(platform, callbackContext);
        } else {
            return false;
        }
        return true;
    }

    private void openShare (String title, String imageUrl, String desc, final CallbackContext callbackContext) {
        Logger.d("openShare");
        UMShareListener umShareListener = new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                //分享开始的回调
            }
            @Override
            public void onResult(SHARE_MEDIA platform) {
                Logger.d("openShare:onResult", "platform"+platform);
                callbackContext.success();
            }

            @Override
            public void onError(SHARE_MEDIA platform, Throwable t) {
                Logger.d("openShare:onError", "platform"+platform);
                if(t!=null){
                    Logger.d("openShare:onError", "throw:"+t.getMessage());
                    callbackContext.error(t.getMessage());
                } else {
                    callbackContext.error("error");
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Logger.d("openShare:onCancel", "platform"+platform);
                callbackContext.error("cancel");
            }
        };
        UMImage image = new UMImage(this.activity, imageUrl);
        cordova.setActivityResultCallback(this);
        new ShareAction(this.activity).withText(title).withMedia(image).withSubject(desc)
                .setDisplayList(SHARE_MEDIA.SINA,SHARE_MEDIA.QQ,SHARE_MEDIA.WEIXIN)
                .setCallback(umShareListener).open();
    }

    private void auth (SHARE_MEDIA platform, final CallbackContext callbackContext) {
        Logger.d("auth");
        UMAuthListener umAuthListener = new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                //授权开始的回调
            }
            @Override
            public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
                Logger.d("auth:onComplete", "platform"+platform);
                JSONObject jsonObject = new JSONObject(data);
                callbackContext.success(jsonObject);
            }

            @Override
            public void onError(SHARE_MEDIA platform, int action, Throwable t) {
                Logger.d("auth:onError", "platform"+platform);
                if(t!=null){
                    Log.d("throw","throw:"+t.getMessage());
                    callbackContext.error(t.getMessage());
                } else {
                    callbackContext.error("error");
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform, int action) {
                Logger.d("auth:onCancel", "platform"+platform);
                callbackContext.error("cancel");
            }
        };
        cordova.setActivityResultCallback(this);
        UMShareAPI.get(this.activity).getPlatformInfo(this.activity, platform, umAuthListener);
    }

    private SHARE_MEDIA getPlatform (int platform) {
        if(platform == WEIXIN) {
            return SHARE_MEDIA.WEIXIN;
        } else if (platform == QQ) {
            return SHARE_MEDIA.QQ;
        } else if (platform == WEIBO) {
            return SHARE_MEDIA.SINA;
        } else {
            return null;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Logger.d("onActivityResult");
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this.activity).onActivityResult(requestCode,resultCode,data);
    }

    private static class Logger {
        private static String TAG = "UM";
        private static boolean DEBUG = true;
        public static void d(String str) {
            if (DEBUG) {
                Log.d(TAG, str);
            }
        }

        public static void d(String str1, String str2) {
            if (DEBUG) {
                Log.d(TAG, str1+":"+str2);
            }
        }
    }
}
